package mo.org.cm309.shoppingcart.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mo.org.cm309.shoppingcart.entity.Role;

import org.apache.log4j.Logger;

public class RoleDAO extends BaseDAO {
	private static RoleDAO instance;
	static Logger logger = Logger.getLogger(RoleDAO.class);
	
	public RoleDAO() {
		super();
	}
	
	public static synchronized RoleDAO getInstance() {
		logger.info("Get Connection.");
		if (instance == null) {
			instance = new RoleDAO();
		}
		return instance;
	}
	
	public List<Role> findByWhereOrderClause(String whereClause, String orderClause) {
		List<Role> list = new ArrayList<Role>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = getConnection();
			conn.setAutoCommit(true);
			stmt = conn.createStatement();
			String sql = "select * from role " + whereClause + " " + orderClause;
			logger.info(sql);
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				int id      = rs.getInt("id");
				String name = rs.getString("name");
				Role role   = new Role(id, name);
				list.add(role);
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
				}
				if (rs != null) {
					rs.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
			releaseConnection(conn);
		}

		return list;

	}
	
	
	public List<Role> findByWhereClause(String whereClause) {
		return findByWhereOrderClause(whereClause, "");
	}

	public List<Role> findAll() {
		return findByWhereClause("");
	}

	public Role findById(long id) {
		List<Role> us = findByWhereOrderClause("where id=" + id, "order by id");
		if (us.size() > 0)
			return (Role) us.get(0);
		return null;
	}
}
